from celery import shared_task
import threading

from CeleryTimedTask.HttpTestcase.testsuite_task import run_testsuite
from apps.HttpTestcase.core.http_global_variable_pool import Variable_Pool
from HttpTestcase.core.http_dlient import HttpSession
from HttpTestcase.core.utils import get_version
from HttpTestcase.models import TestsuiteSet
from test import DingDingWebHook
from apps.SystemService.models.parameter import ParameterModels
import json


def run_testsuiteset(testsuites_set_list=None, version=None):
    statistics = {
        'testcase_num': 0,
        'pass_num': 0,
        'fail_num': 0,
        'elapsed_ms': 0,
        'version': ''
    }
    # 循环场景集列表
    for testsuite_set in testsuites_set_list:
        # http_session = HttpSession()
        http_session_params = Variable_Pool()
        # 循环查询场景集下所有场景
        testsuiteset2testsuite_list = testsuite_set.testsuite_set2testsuite.all()
        # 循环每个场景
        for suite2set in testsuiteset2testsuite_list:
            if suite2set.is_execute:
                loop_count = suite2set.loop_count
                # 场景集下数据所绑定的场景
                testsuite = [suite2set.testsuite]
                for item in range(loop_count):
                    testsuite_statistics = run_testsuite(testsuite=testsuite, version=version, http_session_params=http_session_params, is_testsuite_set=True)
                    statistics['testcase_num'] = statistics['testcase_num'] + testsuite_statistics.get('testcase_num')
                    statistics['pass_num'] = statistics['pass_num'] + testsuite_statistics.get('pass_num')
                    statistics['fail_num'] = statistics['fail_num'] + testsuite_statistics.get('fail_num')
                    statistics['elapsed_ms'] = statistics['elapsed_ms'] + testsuite_statistics.get('elapsed_ms')
                    statistics['version'] = testsuite_statistics.get('version')


        is_dingTalk = testsuite_set.dingTalk
        if is_dingTalk:
            # 发送报告到钉钉
            parameter = ParameterModels.objects.filter(key='DingTalk').first()
            value = json.loads(parameter.value)
            webhook = value.get('webhook')
            secret = value.get('secret')
            dingTalk = DingDingWebHook(url=webhook, secret=secret)
            dingTalk.send_meassage(testcase_num=statistics.get('testcase_num'), pass_num=statistics.get('pass_num'), fail_num=statistics.get('fail_num'), elapsed_ms=statistics.get('elapsed_ms'),
                                   version=statistics.get('version'),
                                   report_url='http://localhost:8080/#/reports_suite/{0}'.format(statistics.get('version')))


@shared_task(name='批量执行测试场景集:apps.CeleryTimedTask.HttpTestcase.testsuiteset_taks.batch_exec_testsuiteset')
def batch_exec_testsuiteset(testsuites_set_list=None, version=None):
    if not version:
        version = get_version()

    if isinstance(testsuites_set_list, str):
        testsuites_set = eval(testsuites_set_list) if isinstance(eval(testsuites_set_list), list) else []
    testsuiteset_list = TestsuiteSet.objects.filter(id__in=testsuites_set_list, is_delete=False)

    # 线程数量
    thread_num = 5
    # Q每个线程多少任务   R剩余
    Q, R = divmod(len(testsuiteset_list), thread_num)

    # 生成线程对应数量的列表
    testsuite_temp = [[] for i in range(thread_num)]

    # 每次取出Q个用例场景放入testcases_temp里的list中
    for i in range(thread_num):
        testsuite_temp[i] = testsuiteset_list[i * Q:(i + 1) * Q]

    for i in range(R):
        testsuite_temp[i].append(testsuiteset_list[Q * R + i])

        # 给线程分配任务并启动
    threads = []
    for y in range(thread_num):
        t = threading.Thread(target=run_testsuiteset, args=(testsuite_temp[y], version))
        threads.append(t)

    for t in threads:
        t.start()
